<!--角色管理 role_manager-->

<template>
    <div id="role_manager">
        <!--搜索框-->
        <div class="above_box">
            <div class="page_title"><i class="el-icon-search"></i><span style="margin-left:10px ">搜索角色</span></div>
            <el-row>
                <el-col :span="6" style="padding:0 50px">
                    <el-input
                            placeholder="请输入角色名称"
                            v-model="searchForm.roleName"
                            prefix-icon="el-icon-user"
                            autofocus
                            clearable>
                    </el-input>
                </el-col>
                <el-col :span="6" style="padding:0 50px;margin-left: -50px">
                    <el-select
                            style="width: 100%"
                            v-model="searchForm.roleStatus"
                            clearable
                            placeholder="请选择角色状态">
                        <el-option label="正常" value="正常"></el-option>
                        <el-option label="禁用" value="禁用"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="12">
                    <el-button
                            type="success"
                            icon="el-icon-document"
                            @click.stop.prevent="()=>{totalData=[...roleData]} ">查看全部
                    </el-button>
                    <el-button
                            type="primary"
                            icon="el-icon-search"
                            @click.stop.prevent="()=>{totalData=outsideMethod.matchArrayData(roleData,{...searchForm})} ">
                        搜索
                    </el-button>
                    <el-button type="primary" icon="el-icon-refresh-left"
                               @click.stop.prevent="outsideMethod.resetBtn(searchForm)" plain>重置
                    </el-button>
                </el-col>
            </el-row>
        </div>
        <!--信息框-->
        <div class="below_box">
            <div class="page_title">
                <i class="el-icon-s-custom"></i><span style="margin: 0 25px 0 10px">角色信息</span>
                <span style="position: relative">
                    <el-button
                            class="role_below_title_btn"
                            type="success"
                            icon="el-icon-document-add"
                            @click="()=>{dialogFormState='新增'}"
                            round>新增角色</el-button>
                </span>
            </div>
            <div style="margin:0 50px">
                <el-table
                        :data="tableData"
                        style="width: 100%"
                        :stripe=true
                        :border=true
                        :header-cell-style="{backgroundColor:'#409EFF',textAlign:'center',color:'white'}"
                        :cell-style="{textAlign:'center'}"
                        slot="empty"
                >
                    <el-table-column
                            prop="roleName"
                            label="角色名称"
                            min-width="20%">
                    </el-table-column>
                    <el-table-column
                            label="角色描述"
                            min-width="20%">
                        <template slot-scope="scope">
                            <span :class="{noticeWordColor:scope.row.roleDesc==='暂无描述'}">{{scope.row.roleDesc}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="createTime"
                            label="创建时间"
                            min-width="20%">
                    </el-table-column>
                    <el-table-column
                            label="角色状态"
                            min-width="20%">
                        <template slot-scope="scope">
                            <el-tag
                                    :type="scope.row.roleStatus === '正常' ? 'success' : 'danger'"
                                    disable-transitions>{{scope.row.roleStatus}}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column
                            fixed="right"
                            label="操作"
                            min-width="20%">
                        <template slot-scope="scope">
                            <el-button type="text" @click="()=>{dialogFormState = '修改';roleForm={...scope.row}}">修改
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <el-pagination
                    style="text-align: center;padding-top: 25px"
                    background
                    layout="prev, pager, next"
                    :current-page="currentPage"
                    :total="totalCount"
                    @current-change="(nowPage)=>{currentPage=nowPage;tableData=outsideMethod.currentPageData(currentPage,pageSize,totalData)}">
            </el-pagination>
        </div>
        <!--新增/修改框-->
        <div>
            <el-dialog :visible="Boolean(dialogFormState)"
                       :before-close="(done)=>{outsideMethod.boxClose(this,done,dialogFormState)}"
                       center>
                <div slot="title">
                    <i :class="{ 'el-icon-document-add':dialogFormState==='新增','el-icon-document':dialogFormState==='修改'}"
                       style="margin-right: 10px"></i>
                    {{dialogFormState}}信息
                </div>

                <div class="p_dialog_box">
                    <el-row :gutter="0" class="p_dialog_box_row">
                        <el-col class="col_left" :span="5">
                            <span><i class="el-icon-s-custom"></i>角色名称：</span>
                        </el-col>
                        <el-col class="col_right" :span="19">
                            <el-input
                                    v-model="roleForm.roleName"
                                    @blur="()=>{outsideMethod.canNotBeNull(roleForm.roleName,'角色名称')}"
                                    placeholder="请输入角色名称"
                                    clearable>
                            </el-input>
                        </el-col>
                    </el-row>
                    <el-row :gutter="0" class="p_dialog_box_row">
                        <el-col class="col_left" :span="5">
                            <span><i class="el-icon-edit-outline"></i>角色描述：</span>
                        </el-col>
                        <el-col class="col_right" :span="19">
                            <el-input
                                    v-model="roleForm.roleDesc"
                                    @blur="()=>{outsideMethod.canNotBeNull(roleForm.roleDesc,'角色描述')}"
                                    placeholder="请输入角色描述"
                                    clearable></el-input>
                        </el-col>
                    </el-row>
                    <el-row :gutter="0" class="p_dialog_box_row">
                        <el-col class="col_left" :span="5">
                            <span><i class="el-icon-s-check"></i>角色权限：</span>
                        </el-col>
                        <el-col class="col_right" :span="19">
                            <el-cascader
                                    style="width: 100%"
                                    size="medium"
                                    v-model="roleForm.authName"
                                    placeholder="请选择角色权限"
                                    :options="allRolePermissions"
                                    :props="{ expandTrigger: 'hover', multiple: true ,checkStrictly: true}"
                                    clearable
                                    collapse-tags
                                    filterable
                                    :show-all-levels="false"
                                    @change="()=>{outsideMethod.canNotBeNull(roleForm.authName,'角色权限')}">
                                <!--上方（Cascader级联选择器）:{
                                v-model：选择内容保存在哪里(数组形式)，
                                options:需要渲染的树结构数据，
                                props：组件的相关配置（结构展开开方式，是否多选，是否取消父子关联选择），
                                clearable:可清空，
                                collapse-tags:折叠多选内容，
                                filterable:可搜索内容，
                                show-all-levels:展示选择内容的完整路径，
                                change：当值发生变化的回调函数
                                }-->
                                <!--<template slot-scope="{ node, data }">
                                    <span>{{ data.label }}</span>
                                    <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                                </template>-->
                            </el-cascader>
                        </el-col>
                    </el-row>
                    <el-row :gutter="0" class="p_dialog_box_row">
                        <el-col class="col_left" :span="5">
                            <span><i class="el-icon-setting"></i>角色状态：</span>
                        </el-col>
                        <el-col style="line-height: 40px;padding-left: 15px" class="col_right" :span="19">
                            <el-radio v-model="roleForm.roleStatus" label="正常">正常</el-radio>
                            <el-radio v-model="roleForm.roleStatus" label="禁用">禁用</el-radio>
                        </el-col>
                    </el-row>
                </div>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormState =''">取 消</el-button>
                    <el-button type="primary"
                               @click="()=>{if(outsideMethod.bothNotBeNull(roleForm)){addOrChangeRequest(roleForm)}}">确
                        定
                    </el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import pMethod from './pmw_common/p_common_method' //公共方法引入
    import {mapActions, mapState, mapGetters, mapMutations} from 'vuex'
    import api from '../../tool/api'
    import http from '../../tool/http'

    export default {
        name: "userManager",
        data() {
            return {
                outsideMethod: {...pMethod},/*外部公共方法*/
                currentPage: 1,//当前页
                pageSize: 10,//页面数据条数
                totalData: [],
                totalCount: 0,

                searchForm: {
                    roleName: '',
                    roleStatus: ''
                },//搜索框内容
                tableData: [],//表格数据

                dialogFormState: '',//弹出框的状态（新增/修改）
                roleForm: {
                    roleName: '',
                    roleStatus: '',
                    roleDesc: '',
                    authName: [],
                },//新增/修改框内容
                allRolePermissions: [],//级联选择器渲染的数据
            }
        },
        computed: {
            ...mapGetters(['roleData', 'detailTotalData']),
        },
        methods: {
            ...mapActions(['getRoleDataAction', 'getDetailTotalDataAction']),
            //...mapActions(['getDetailTotalDataAction']),
            whenTotalDataChanged(newValue) {
                this.totalCount = newValue.length;
                this.tableData = this.outsideMethod.currentPageData(1, this.pageSize, newValue)
            },
            /*修改数据为指定数据格式，针对权限与级联选择器*/
            changeDetailToCascader(needArrData) {
                //console.log(needArrData);
                //value=>id
                //label=>name
                //child=>ismenu
                /*检测数据类型*/
                if (!Array.isArray(needArrData)) return false;
                let arr = [...needArrData];//保持数据
                let dataOne = [];//存放一级权限（元素为对象）
                let dataTwo = [];//存放二级权限（元素为对象）
                /*数据转换*/
                arr.map(item => {
                    //console.log(item);
                    let obj = {value: item.authId, label: item.authName};
                    if (item.authParentId === "无父级权限") {//本就是父级权限
                        //console.log(1);
                        obj.children = [];
                        dataOne.push(obj)
                    } else {
                        //console.log(2);
                        obj.authParentId = item.authParentId;
                        dataTwo.push(obj)
                    }
                });
                /*数据整合*/
                dataOne.map(outItem => {
                    dataTwo.map(inItem => {
                        if (inItem.authParentId === outItem.value) outItem.children.push(inItem)
                    })
                });
                /*return*/
                //console.log(dataOne);
                return dataOne;
            },
            /*/!*修改指定数据格式为详细数据，针对权限与级联选择器*!/
            roleAuthsToCascaderData(roleAuths) {
                /!*检测数据类型*!/
                if (!Array.isArray(roleAuths)) return false;
                let finalData = [];
                roleAuths.map(outItem => {
                    outItem.authParentId ?
                        finalData.push([outItem.authParentId.toString(), outItem.authId.toString()])
                        : finalData.push([outItem.authId.toString()]);
                });
                return finalData;
            },*/
            /*发起修改/新增的请求的方法*/
            async addOrChangeRequest(reqFormData) {
                let reqUrl = '';//定义请求路径
                let reqMethod = '';//定义请求方式
                let reqData = '';//定义请求参数
                /*切换数据形式*/
                reqFormData.authName.map((i, index) => {
                    reqFormData.authName[index] = this.outsideMethod.valueMatchKeys(i[i.length - 1], 'authId', this.detailTotalData)[0];
                });

                if (this.dialogFormState === '新增') {
                    reqUrl = api.addRoleData;
                    reqMethod = 'post';
                    reqData = reqFormData;
                } else if (this.dialogFormState === '修改') {
                    reqUrl = api.updateRoleData;
                    reqMethod = 'put';
                    reqData = reqFormData;
                } else {
                    return false
                }

                await http({
                    url: reqUrl,
                    method: reqMethod,
                    parameter: reqData
                }).then(res => {
                    if (res.data.code === 200) {
                        this.outsideMethod.messageNotic(this.dialogFormState, 'success');
                        /*最后的弹出框要关闭*/
                        this.dialogFormState = '';
                    } else {
                        this.outsideMethod.messageNotic(this.dialogFormState, 'error');
                    }

                }).catch(err => {
                    console.log(err);
                    this.outsideMethod.messageNotic(this.dialogFormState, 'error');
                });

                return false
            }
        },
        watch: {
            totalData(newValue, oldValue) {
                this.whenTotalDataChanged(newValue);
            },
            dialogFormState(newValue, oldValue) {
                if (newValue === '新增') {
                    this.roleForm = {
                        roleName: '',
                        roleStatus: '正常',
                        roleDesc: '',
                        authName: [],
                    }
                }
            },
        },
        async created() {
            /*权限数据*/
            await this.getDetailTotalDataAction();
            /*特定权限数据获取*/
            this.allRolePermissions = this.changeDetailToCascader(this.detailTotalData);

            /*角色数据*/
            await this.getRoleDataAction(this.detailTotalData);
            this.totalData = [...this.roleData];


        },
    }
</script>

<style scoped lang="less">
    * {
        /*margin: 0;
        padding: 0;*/
    }

    .noticeWordColor {
        color: red;
    }

    .page_title {
        border: none;
        border-bottom: 1px solid #CCC8D9;
        font-size: 1.25em;
        padding-bottom: 15px;
        margin-bottom: 15px;
        color: #325b8f;
    }

    .p_dialog_box {
        margin: 0 75px;

        .p_dialog_box_row {
            margin-bottom: 10px;

            .col_left {
                text-align: center;

                span {
                    display: inline-block;
                    height: 40px;
                    line-height: 40px;

                    i {
                        margin-right: 10px;
                    }
                }
            }

            .col_center {

            }

            .col_right {

            }
        }
    }

    .role_below_title_btn {
        position: absolute;
        top: -7px; /*此处高度 =（组件定高40px-父元素高度26px）/ 2 */
    }

    #role_manager {
        /* background-color: #F1F3F7;
         padding: 15px;*/

        .above_box {
            background-color: white;
            border-radius: 10px;
            padding: 25px;
        }

        .below_box {
            margin-top: 15px;
            background-color: white;
            border-radius: 10px;
            padding: 25px;
        }
    }
</style>
